package com.ttdev.mmms.controller.payment;
import com.ttdev.mmms.entity.Account;
import com.ttdev.mmms.entity.MemberInfo;
import com.ttdev.mmms.service.MemberService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 会员付款
 */
@Controller
@RequestMapping("/storePayment")
public  class StorePaymentController {

    @Autowired
    private MemberService memberService;

    // 跳转付款页面
    @RequestMapping("/payment")
    public String MemberPayment(){
        return "/store/storePayment";
    }

    // 查询会员卡号
    @RequestMapping(value = "/select", produces = "application/json;charset=UTF-8")
    public void SelectCard(@RequestParam Integer card, HttpServletResponse response) throws IOException {

//        System.out.println(card);
        List<MemberInfo> list = new ArrayList<>();
        list = memberService.queryMember(card);
        JSONArray jsonArray = JSONArray.fromObject(list);
        // json乱码解决
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(jsonArray.toString());

    }

    // 给会员扣款
    @RequestMapping("/pm")
    public void payment(@RequestParam Integer card, @RequestParam Double price,@RequestParam Integer storeId,HttpServletResponse response) throws IOException {
//        System.out.println(price);
//        System.out.println(card);

        // 扣款
        int i = memberService.payment(card,price);
//        System.out.println(i);

        //入账
        Account account = new Account();
        account.setCardId(card);
        account.setStoreId(storeId);
        account.setMoney(price);
        account.setType("扣款");
//        System.out.println(account.getCardId());
        int cardId = account.getCardId();
        int sId = account.getStoreId();
        double money = account.getMoney();
        String type = account.getType();
        int acc = memberService.account(cardId,sId,money,type);

        if (i != 0){
        JSONObject obj = new JSONObject();
        obj.put("i", i);
        obj.put("acc",acc);
//        System.out.println(obj);
        response.getWriter().write(obj.toString());
        }



    }

}
